﻿using System.ComponentModel;
using System.Runtime.Serialization;
using Core.Helper;

namespace Core.Model.Transmit
{
    /// <summary>
    /// 通道参数
    /// </summary>
    [DataContract]
    public class TransmitChannel : INotifyPropertyChanged
    {
        private int _readTimeout = 2000;
        private int _writeTimeout = 2000;

        [DataMember]
        public string Id { get; set; }
        [DataMember]
        public int Position { get; set; }
        [DataMember]
        public string Name { get; set; }
        //[DataMember]
        public string ChannelType { get; set; }
        //[DataMember]
        public int PollingDelay { get; set; }
        //[DataMember]
        public int ReadTimeout
        {
            get => _readTimeout;
            set
            {
                if (_readTimeout != value)
                {
                    _readTimeout = value;
                    OnPropertyChanged("ReadTimeout");
                }
            }
        }
        //[DataMember]
        public int WriteTimeout
        {
            get => _writeTimeout;
            set
            {
                if (_writeTimeout != value)
                {
                    _writeTimeout = value;
                    OnPropertyChanged("WriteTimeout");
                }
            }
        }
        //[DataMember]
        public string Ip { get; set; }
        //[DataMember]
        public int Port { get; set; }
        //[DataMember]
        public string Comport { get; set; }
        //[DataMember]
        public int Baudrate { get; set; }
        //[DataMember]
        public string Parity { get; set; }
        //[DataMember]
        public int DataBits { get; set; }
        //[DataMember]
        public string StopBits { get; set; }

        [DataMember]
        public bool IsConnected => Global.NetAccess.IsChannelConnected(this.Id);

        public TransmitChannel()
        {
            Id = IdHelper.GuidToString();
        }

        public TransmitChannel Clone(string newId, string newName)
        {
            TransmitChannel channel = new TransmitChannel();
            channel.Id = newId;
            channel.Name = newName;
            channel.Baudrate = Baudrate;
            channel.ChannelType = ChannelType;
            channel.Comport = Comport;
            channel.DataBits = DataBits;
            channel.StopBits = StopBits;
            channel.Parity = Parity;
            channel.Ip = Ip;
            channel.Port = Port;
            channel.PollingDelay = PollingDelay;
            channel.WriteTimeout = WriteTimeout;
            channel.ReadTimeout = ReadTimeout;
            return channel;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
